﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Aspose.Cells.Charts;
using FastReport;
using FastReport.Data;
using FastReport.Export.Image;
using FastReport.Export.OoXML;
using FastReport.Export.Pdf;
using FastReport.Export.Zpl;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Business.Entitys.Common.Dto.PrintExecute;
using SHZY.Business.Entitys.Dto.customerappeal;
using SHZY.Business.Entitys.Dto.customerfile;
using SHZY.Business.Entitys.Dto.customermeasure;
using SHZY.Business.Entitys.Dto.customersurver;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Entitys.OA;
using SHZY.Business.Interfaces;
using SHZY.Business.Interfaces.VideoRecording;
using SHZY.Business.OA;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.FR;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Message.Interfaces.Message;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：纠错和预防措施处理单.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiCustomerMeasure", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiCustomerMeasureService : IQmsBusiCustomerMeasureService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiCustomerMeasureEntity> _repository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 文件服务.
        /// </summary>
        private readonly IFileManager _fileManager;

        /// <summary>
        /// OA.
        /// </summary>

        private readonly QmsOAService _qmsOAService;

        private readonly IMessageService _messageService;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiCustomerMeasureService"/>类型的新实例.
        /// </summary>
        public QmsBusiCustomerMeasureService(
            ISqlSugarRepository<QmsBusiCustomerMeasureEntity> qmsBusiCustomerMeasureRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager, IFileManager fileManager, QmsOAService qmsOAService, IMessageService messageService)
        {
            _repository = qmsBusiCustomerMeasureRepository;
            _dataInterfaceService = dataInterfaceService;
            _db = context.AsTenant();
            _userManager = userManager;
            _fileManager = fileManager;
            _qmsOAService = qmsOAService;
            _messageService = messageService;
        }

        /// <summary>
        /// 获取纠错和预防措施处理单.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var customerid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == id).Select(it => new { id = it.Id }).FirstAsync();
            var customermeasuredata = await _repository.Context.Queryable<QmsBusiCustomerMeasureEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.id).Select(it => new QmsBusiCustomerMeasureListOutput() { id = it.Id, nonDescription = it.NonDescription, causeAnalysis = it.CauseAnalysis, completionDate = it.CompletionDate, nonGood = it.NonGood, isFinish = it.IsFinish, finishQty = it.FinishQty, finishResponsibleUserId = it.FinishResponsibleUserId, finishCompletionDate = it.FinishCompletionDate, isSemi = it.IsSemi, semiQty = it.SemiQty, semiResponsibleUserId = it.SemiResponsibleUserId, semiCompletionDate = it.SemiCompletionDate, isInventory = it.IsInventory, inventoryQty = it.InventoryQty, inventoryResponsibleUserId = it.InventoryResponsibleUserId, inventoryCompletionDate = it.InventoryCompletionDate, isOther = it.IsOther, otherQyt = it.OtherQyt, otherResponsibleUserId = it.OtherResponsibleUserId, otherCompletionDate = it.OtherCompletionDate, measureRemark = it.MeasureRemark, measureResponsibleUserId = it.MeasureResponsibleUserId, measureCompletionDate = it.MeasureCompletionDate, evaluationRemark = it.EvaluationRemark, evaluationResponsibleUserId = it.EvaluationResponsibleUserId, evaluationCompletionDate = it.EvaluationCompletionDate, status = it.Status }).FirstAsync();
            var image = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.id && it.Type == 0).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
            if (customermeasuredata == null)
            {

                customermeasuredata = new QmsBusiCustomerMeasureListOutput { id = "", nonDescription = "", causeAnalysis = "", completionDate = null, nonGood = "", isFinish = null, finishQty = "", finishResponsibleUserId = "", finishCompletionDate = null, isSemi = null, semiQty = "", semiResponsibleUserId = "", semiCompletionDate = null, isInventory = null, inventoryQty = "", inventoryResponsibleUserId = "", isOther = null, otherQyt = "", otherResponsibleUserId = "", otherCompletionDate = null, measureRemark = "", measureResponsibleUserId = "", measureCompletionDate = null, evaluationRemark = "", evaluationResponsibleUserId = "", evaluationCompletionDate = null, status = null, ImageList = image };
            }
            if (!string.IsNullOrEmpty(customermeasuredata.id))
            {
                customermeasuredata.ImageList = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.id && it.Type == 3).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
            }
            return customermeasuredata;
        }
        /// <summary>
        /// 新建纠错和预防措施处理单.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] QmsBusiCustomerMeasureCrInput input)
        {
            var CustomerMeasure = input.Adapt<QmsBusiCustomerMeasureEntity>();
            CustomerMeasure.Id = SnowflakeIdHelper.NextId();
            CustomerMeasure.EnabledMark = 1;
            //List<QmsBusiCustomerFileEntity> qmsbusicustomerfilelist = new List<QmsBusiCustomerFileEntity>();
            //循环添加文件信息
            //for (var i = 0; i < input.FileInfo.Count; i++)
            //{
            //    QmsBusiCustomerFileEntity CustomerFileEntity = new QmsBusiCustomerFileEntity();
            //    CustomerFileEntity.CustomerId = CustomerMeasure.Id;
            //    CustomerFileEntity.FileInfo = JsonConvert.SerializeObject(input.FileInfo[i]);
            //    CustomerFileEntity.Type = input.FileInfo[i].Type;
            //    CustomerFileEntity.Remark = input.FileInfo[i].Remark;
            //    CustomerFileEntity.CreatorUserId = _userManager.UserId;
            //    CustomerFileEntity.CreatorTime = DateTime.Now;
            //    qmsbusicustomerfilelist.Add(CustomerFileEntity);
            //}
            try
            {
                var customermeasure = await _repository.Context.Insertable(CustomerMeasure).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                //var customerfile = await _repository.Context.Insertable(qmsbusicustomerfilelist).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (!(customermeasure > 0))
                {
                    _db.RollbackTran();
                    throw Oops.Oh(ErrorCode.COM1000);
                }
                _db.BeginTran();
                //提交OA暂时没写
                //Content content = new Content()
                //{
                //    type = "Processing",
                //    orderNumber = "",
                //    title = "客诉-客户名称-纠正和预防措施流程",
                //    context = "请查阅附件，请审批。",
                //    attachments = "",
                //    attachmentsPath = ""
                //};
                //await _qmsOAService.SendMessageAsync(content);
            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                throw Oops.Oh("错误信息：" + ex.Message);
            }
        }

        /// <summary>
        /// 更新纠错和预防措施处理单.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] QmsBusiCustomerMeasureUpInput input)
        {
            var entity = input.Adapt<QmsBusiCustomerMeasureEntity>();
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.NonDescription,
                it.CauseAnalysis,
                it.CompletionDate,
                it.NonGood,
                it.IsFinish,
                it.FinishQty,
                it.FinishResponsibleUserId,
                it.FinishCompletionDate,
                it.IsSemi,
                it.SemiQty,
                it.SemiResponsibleUserId,
                it.SemiCompletionDate,
                it.IsInventory,
                it.InventoryQty,
                it.InventoryResponsibleUserId,
                it.InventoryCompletionDate,
                it.IsOther,
                it.OtherQyt,
                it.OtherResponsibleUserId,
                it.OtherCompletionDate,
                it.MeasureRemark,
                it.MeasureResponsibleUserId,
                it.MeasureCompletionDate,
                it.EvaluationRemark,
                it.EvaluationResponsibleUserId,
                it.EvaluationCompletionDate,
                it.Status,
                //it.EnabledMark,
            }).ExecuteCommandAsync();

            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 打印纠错和预防措施处理单.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <param name="exportType">打印类型.</param>
        /// <returns></returns>
        [HttpPost("fastreportPrintCustomerMeasure")]
        public async Task<dynamic> PrintCustomerMeasure([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion
            //获取数据源
            var customeid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == input.formDataId).Select(it => new QmsBusiCustomerComplaintEntity { Id = it.Id }).FirstAsync();
            var primary = await _repository.Context.Queryable<QmsBusiCustomerMeasureEntity>().Where(it => it.CustomerId == customeid.Id && it.DeleteMark == null).Select(it =>
            new QmsBusiCustomerMeasureListOutput()
            {
                id = it.Id,
                nonDescription = it.NonDescription,
                causeAnalysis = it.CauseAnalysis,
                _completionDate = it.CompletionDate == null ? "" : SqlFunc.ToDate(it.CompletionDate).ToString("yyyy-MM-dd"),
                nonGood = it.NonGood,
                isFinish = it.IsFinish,
                finishQty = it.FinishQty,
                finishResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.FinishResponsibleUserId).Select(p => p.RealName),
                _finishCompletionDate = it.FinishCompletionDate == null ? "" : SqlFunc.ToDate(it.FinishCompletionDate).ToString("yyyy-MM-dd"),
                isSemi = it.IsSemi,
                semiQty = it.SemiQty,
                semiResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.SemiResponsibleUserId).Select(p => p.RealName),
                _semiCompletionDate = it.SemiCompletionDate == null ? "" : SqlFunc.ToDate(it.SemiCompletionDate).ToString("yyyy-MM-dd"),
                isInventory = it.IsInventory,
                inventoryQty = it.InventoryQty,
                inventoryResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.InventoryResponsibleUserId).Select(p => p.RealName),
                _inventoryCompletionDate = it.InventoryCompletionDate == null ? "" : SqlFunc.ToDate(it.InventoryCompletionDate).ToString("yyyy-MM-dd"),
                isOther = it.IsOther,
                otherQyt = it.OtherQyt,
                otherResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.OtherResponsibleUserId).Select(p => p.RealName),
                _otherCompletionDate = it.OtherCompletionDate == null ? "" : SqlFunc.ToDate(it.OtherCompletionDate).ToString("yyyy-MM-dd"),
                measureRemark = it.MeasureRemark,
                _measureCompletionDate = it.MeasureCompletionDate == null ? "" : SqlFunc.ToDate(it.MeasureCompletionDate).ToString("yyyy-MM-dd"),
                measureResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.MeasureResponsibleUserId).Select(p => p.RealName),
                evaluationRemark = it.EvaluationRemark,
                evaluationResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.EvaluationResponsibleUserId).Select(p => p.RealName),
                _evaluationCompletionDate = it.EvaluationCompletionDate == null ? "" : SqlFunc.ToDate(it.EvaluationCompletionDate).ToString("yyyy-MM-dd"),
                status = it.Status
            }).ToDataTableAsync();
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }

        /// <summary>
        /// 调用OA接口.
        /// </summary>
        /// <param name="input">input.</param>
        /// <returns></returns>
        [HttpPost("SubmitOA")]
        public async Task SubmitOA(ContentModel input, FastReportExportType exportType = FastReportExportType.PDF)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion
            //获取数据源
            var customeid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == input.formDataId).Select(it => new QmsBusiCustomerComplaintEntity { Id = it.Id, No = it.No, CustomerName = it.CustomerName, CreatorUserId = it.CreatorUserId }).FirstAsync();
            var appealid = await _repository.Context.Queryable<QmsBusiCustomerAppealEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customeid.Id).Select(it => new QmsBusiCustomerAppealEntity() { AppealUserId = it.AppealUserId }).FirstAsync();
            DataTable primary = new DataTable();
            if (input.printConfigId == "573376979706308997")
            {
                primary = await _repository.Context.Queryable<QmsBusiCustomerAppealEntity>().Where(it => it.CustomerId == customeid.Id && it.DeleteMark == null).
               Select(it => new QmsBusiCustomerAppealListOutput()
               {
                   id = it.Id,
                   appeaDepartId = SqlFunc.Subqueryable<OrganizeEntity>().Where(p => p.Id == it.AppeaDepartId).Select(p => p.FullName),
                   appealUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.AppealUserId).Select(p => p.RealName),
                   appeaDate = it.AppeaDate,
                   appeaNo = it.AppeaNo,
                   projectName = it.ProjectName,
                   projectNameTwo = it.ProjectNameTwo,
                   materialNo = it.MaterialNo,
                   materialName = it.MaterialName,
                   qty = it.Qty,
                   checkedUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.CheckedUserId).Select(p => p.RealName),
                   problemDescription = it.ProblemDescription,
                   appealDescription = it.AppealDescription,
                   proofMaterials = it.ProofMaterials,
                   remark = it.Remark,
                   status = it.Status
               }).ToDataTableAsync();
            }
            if (input.printConfigId == "575213750031221958")
            {
                primary = await _repository.Context.Queryable<QmsBusiCustomerMeasureEntity>().Where(it => it.CustomerId == customeid.Id && it.DeleteMark == null).Select(it =>
            new QmsBusiCustomerMeasureListOutput()
            {
                id = it.Id,
                nonDescription = it.NonDescription,
                causeAnalysis = it.CauseAnalysis,
                _completionDate = it.CompletionDate == null ? "" : SqlFunc.ToDate(it.CompletionDate).ToString("yyyy-MM-dd"),
                nonGood = it.NonGood,
                isFinish = it.IsFinish,
                finishQty = it.FinishQty,
                finishResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.FinishResponsibleUserId).Select(p => p.RealName),
                _finishCompletionDate = it.FinishCompletionDate == null ? "" : SqlFunc.ToDate(it.FinishCompletionDate).ToString("yyyy-MM-dd"),
                isSemi = it.IsSemi,
                semiQty = it.SemiQty,
                semiResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.SemiResponsibleUserId).Select(p => p.RealName),
                _semiCompletionDate = it.SemiCompletionDate == null ? "" : SqlFunc.ToDate(it.SemiCompletionDate).ToString("yyyy-MM-dd"),
                isInventory = it.IsInventory,
                inventoryQty = it.InventoryQty,
                inventoryResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.InventoryResponsibleUserId).Select(p => p.RealName),
                _inventoryCompletionDate = it.InventoryCompletionDate == null ? "" : SqlFunc.ToDate(it.InventoryCompletionDate).ToString("yyyy-MM-dd"),
                isOther = it.IsOther,
                otherQyt = it.OtherQyt,
                otherResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.OtherResponsibleUserId).Select(p => p.RealName),
                _otherCompletionDate = it.OtherCompletionDate == null ? "" : SqlFunc.ToDate(it.OtherCompletionDate).ToString("yyyy-MM-dd"),
                measureRemark = it.MeasureRemark,
                _measureCompletionDate = it.MeasureCompletionDate == null ? "" : SqlFunc.ToDate(it.MeasureCompletionDate).ToString("yyyy-MM-dd"),
                measureResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.MeasureResponsibleUserId).Select(p => p.RealName),
                evaluationRemark = it.EvaluationRemark,
                evaluationResponsibleUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.EvaluationResponsibleUserId).Select(p => p.RealName),
                _evaluationCompletionDate = it.EvaluationCompletionDate == null ? "" : SqlFunc.ToDate(it.EvaluationCompletionDate).ToString("yyyy-MM-dd"),
                status = it.Status
            }).ToDataTableAsync();
            }

            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            //获取文件路径
            string? AppUrl = string.IsNullOrEmpty(App.Configuration["SHZY_APP:AppUrl"]) ? string.Empty : App.Configuration["SHZY_APP:AppUrl"];
            string? datetimestring = DateTime.Now.ToString("yyyyMMddHHmmss");
            string? path = "";
            if (input.type == "Complaint")
            {
                path = Path.Combine(AppUrl, "OA", "Complaint", datetimestring + customeid.No + ".pdf");
            }
            if (input.type == "Processing")
            {
                path = Path.Combine(AppUrl, "OA", "Processing", datetimestring + customeid.No + ".pdf");
            }
            Report report = new Report();
            report.Load(filePath);
            if (dicList != null && dicList.Count > 0)
            {
                foreach (KeyValuePair<string, DataTable> dic in dicList)
                {
                    if (!dic.Key.IsNullOrEmpty() && !dic.Value.IsNullOrEmpty())
                    {
                        report.RegisterData(dic.Value, dic.Key.ToString());
                    }
                }
            }
            if (report.Report.Prepare())
            {
                PDFExport pDFExport = new PDFExport();
                pDFExport.ShowProgress = false;
                report.Report.Export(pDFExport, path);
                report.Dispose();
                pDFExport.Dispose();
            }
            //判断文件是否存在存在调用OA接口
            if (File.Exists(path))
            {
                //获取路径下的文件名称
                string fileName = Path.GetFileName(path);
                //创建对象
                Content content = new Content()
                {
                    type = input.type,
                    orderNumber = customeid.No,
                    title = input.type == "Complaint" ? "客诉-" + customeid.CustomerName + "质量申诉单" : "客诉" + customeid.CustomerName + "纠正和预防措施单"/*"客诉-客户名称-纠正和预防措施流程（质量申诉）"*/,
                    context = "请查阅附件，请审批。",
                    //title = input.title,
                    //context = input.context,
                    attachments = fileName, /*Path.Combine(datetimestring, customeid.No)*/
                    attachmentsPath = path,
                    sqrgh = input.type == "Complaint" ? appealid.AppealUserId : customeid.CreatorUserId,
                    pbbqrrgh = customeid.CreatorUserId,

                };
                await _qmsOAService.SendMessageAsync(content);
            }
            else
            {
                //抛出异常提醒
                throw Oops.Bah("文件不存在！");
            }
        }

        /// <summary>
        /// 纠正和预防措施处理单确认接口(发送邮件并调用OA接口).
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SubmitMeasure")]
        public async Task SubmitMeasure(string id, [FromBody] QmsBusiCustomerMeasureModel input)
        {
            bool isLogin = true;
            var customermeasureid = _repository.Context.Queryable<QmsBusiCustomerMeasureEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == id).First();
            //查客诉主表的客户名称产品名称缺陷类别
            var customerid = _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == customermeasureid.CustomerId).First();
            var appealid = await _repository.Context.Queryable<QmsBusiCustomerAppealEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.Id).Select(it => new QmsBusiCustomerAppealEntity() { AppealUserId = it.AppealUserId }).FirstAsync();
            if ((customermeasureid.IsMeasure == 0 || customermeasureid.IsMeasure == null) && !string.IsNullOrEmpty(input.nonDescription) && !string.IsNullOrEmpty(input.causeAnalysis) && input.completionDate != null && !string.IsNullOrEmpty(input.nonGood) && !string.IsNullOrEmpty(input.measureRemark) && !string.IsNullOrEmpty(input.measureResponsibleUserId) && input.measureCompletionDate != null && !string.IsNullOrEmpty(input.evaluationRemark) && !string.IsNullOrEmpty(input.evaluationResponsibleUserId) && input.evaluationCompletionDate != null)
            {
                //要发送的用户字符串
                string userlist = "";
                var finishResponsibleUserId = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.finishResponsibleUserId).FirstAsync();
                var semiResponsibleUserId = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.semiResponsibleUserId).FirstAsync();
                var inventoryResponsibleUserId = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.inventoryResponsibleUserId).FirstAsync();
                var otherResponsibleUserId = await _repository.Context.Queryable<UserEntity>().Where(it => it.Id == input.otherResponsibleUserId).FirstAsync();
                //成品数量-半成品数量-库存数量-其他责任人
                if (!string.IsNullOrEmpty(input.finishResponsibleUserId))
                {
                    userlist += finishResponsibleUserId.Id + ",";
                }
                if (!string.IsNullOrEmpty(input.inventoryResponsibleUserId))
                {
                    userlist += semiResponsibleUserId.Id + ",";
                }
                if (!string.IsNullOrEmpty(input.inventoryResponsibleUserId))
                {
                    userlist += inventoryResponsibleUserId.Id + ",";
                }
                if (!string.IsNullOrEmpty(input.otherResponsibleUserId))
                {
                    userlist += otherResponsibleUserId.Id;
                }

                //string userlist = finishResponsibleUserId.Id + "," + semiResponsibleUserId.Id + "," + inventoryResponsibleUserId.Id + "," + otherResponsibleUserId.Id;
                JArray jArray = new JArray();
                JObject jObject = new JObject();
                //jObject.Add("text", "客诉-客户名称-产品名称-缺陷类别");
                jObject.Add("text", "客诉-" + customerid.CustomerName + "-" + customerid.ProductName + "-" + customerid.DefectCategory);
                jObject.Add("nonDescription", input.nonDescription);
                jObject.Add("causeAnalysis", input.causeAnalysis);
                jObject.Add("completionDate", input.completionDate);
                jObject.Add("nonGood", input.nonGood);
                if (input.isFinish != null && !string.IsNullOrEmpty(input.finishResponsibleUserId) && input.finishCompletionDate != null)
                {
                    jObject.Add("isFinish", input.isFinish);
                    jObject.Add("finishResponsibleUserId", input.finishResponsibleUserId);
                    jObject.Add("finishCompletionDate", input.finishCompletionDate);
                }
                else
                {
                    jObject.Add("isFinish", "");
                    jObject.Add("finishResponsibleUserId", "");
                    jObject.Add("finishCompletionDate", "");
                }
                if (input.isSemi != null && !string.IsNullOrEmpty(input.semiResponsibleUserId) && input.semiCompletionDate != null)
                {
                    jObject.Add("isSemi", input.isSemi);
                    jObject.Add("semiResponsibleUserId", input.semiResponsibleUserId);
                    jObject.Add("semiCompletionDate", input.semiCompletionDate);
                }
                else
                {
                    jObject.Add("isSemi", "");
                    jObject.Add("semiResponsibleUserId", "");
                    jObject.Add("semiCompletionDate", "");
                }
                if (input.isInventory != null && !string.IsNullOrEmpty(input.inventoryResponsibleUserId) && input.inventoryCompletionDate != null)
                {
                    jObject.Add("isInventory", input.isInventory);
                    jObject.Add("inventoryResponsibleUserId", input.inventoryResponsibleUserId);
                    jObject.Add("inventoryCompletionDate", input.inventoryCompletionDate);
                }
                else
                {
                    jObject.Add("isInventory", "");
                    jObject.Add("inventoryResponsibleUserId", "");
                    jObject.Add("inventoryCompletionDate", "");
                }
                if (input.isOther != null && !string.IsNullOrEmpty(input.otherResponsibleUserId) && input.otherCompletionDate != null)
                {
                    jObject.Add("isOther", input.isOther);
                    jObject.Add("otherResponsibleUserId", input.otherResponsibleUserId);
                    jObject.Add("otherCompletionDate", input.otherCompletionDate);
                }
                else
                {
                    jObject.Add("isOther", "");
                    jObject.Add("otherResponsibleUserId", "");
                    jObject.Add("otherCompletionDate", "");
                }
                jObject.Add("measureRemark", input.measureRemark);
                jObject.Add("measureResponsibleUserId", input.measureResponsibleUserId);
                jObject.Add("measureCompletionDate", input.measureCompletionDate);
                jObject.Add("evaluationRemark", input.evaluationRemark);
                jObject.Add("evaluationResponsibleUserId", input.evaluationResponsibleUserId);
                jObject.Add("evaluationCompletionDate", input.evaluationCompletionDate);
                jArray.Add(jObject);
                _messageService.AddMessageEvent("CustomerMeasure", userlist, jArray.ToJsonString(), null, isLogin);
                //修改状态为已发送
                await _repository.Context.Updateable<QmsBusiCustomerMeasureEntity>().SetColumns(it => new QmsBusiCustomerMeasureEntity { IsMeasure = 1 }).Where(it => it.Id == id).ExecuteCommandAsync();
                //var content = input.Adapt<ContentModel>();
                var content = new ContentModel()
                {
                    formDataId = input.formDataId,
                    printConfigId = input.printConfigId,
                    formCustomerId = input.formCustomerId,
                    type = input.type,
                    title = input.type == "Complaint" ? "客诉-" + customerid.CustomerName + "质量申诉单" : "客诉" + customerid.CustomerName + "纠正和预防措施单"/*"客诉-客户名称-纠正和预防措施流程（质量申诉）"*/,
                    context = "请查阅附件，请审批。",
                    sqrgh = input.type == "Complaint" ? appealid.AppealUserId : customerid.CreatorUserId,
                    pbbqrrgh = customerid.CreatorUserId,
                };
                //调用OA接口
                await SubmitOA(content);
            }

        }
    }
    public class ContentModel
    {
        /// <summary>
        /// 目标id.
        /// </summary>
        public string formDataId { get; set; }

        /// <summary>
        /// 打印id.
        /// </summary>
        public string printConfigId { get; set; }

        /// <summary>
        /// 客户id.
        /// </summary>
        public string formCustomerId { get; set; }

        /// <summary>
        /// 打印的类型Complaint质量申诉单Processing纠正和预防措施处理单.
        /// </summary>
        public string type { get; set; }

        /// <summary>
        /// 标题.
        /// </summary>
        public string title { get; set; }

        /// <summary>
        /// 内容.
        /// </summary>
        public string context { get; set; }

        /// <summary>
        /// 品保部确认人工号.
        /// </summary>
        public string pbbqrrgh { get; set; }

        /// <summary>
        /// 申请人工号.
        /// </summary>
        public string sqrgh { get; set; }
    }
    public class QmsBusiCustomerMeasureModel : ContentModel
    {

        /// <summary>
        /// 不合格描述.
        /// </summary>
        public string nonDescription { get; set; }

        /// <summary>
        /// 根源分析.
        /// </summary>
        public string causeAnalysis { get; set; }

        /// <summary>
        /// 完成日期.
        /// </summary>
        public DateTime? completionDate { get; set; }

        /// <summary>
        /// 不良品.
        /// </summary>
        public string nonGood { get; set; }

        /// <summary>
        /// 是否勾选成品数量.
        /// </summary>
        public int? isFinish { get; set; }

        /// <summary>
        /// 成品数量.
        /// </summary>
        public string finishQty { get; set; }

        /// <summary>
        /// 成品责任人.
        /// </summary>
        public string finishResponsibleUserId { get; set; }

        /// <summary>
        /// 成品完成日期.
        /// </summary>
        public DateTime? finishCompletionDate { get; set; }

        /// <summary>
        /// 是否勾选半成品数量.
        /// </summary>
        public int? isSemi { get; set; }

        /// <summary>
        /// 半成品数量.
        /// </summary>
        public string semiQty { get; set; }

        /// <summary>
        /// 半成品责任人.
        /// </summary>
        public string semiResponsibleUserId { get; set; }

        /// <summary>
        /// 半成品完成日期.
        /// </summary>
        public DateTime? semiCompletionDate { get; set; }

        /// <summary>
        /// 是否勾选库存数量.
        /// </summary>
        public int? isInventory { get; set; }

        /// <summary>
        /// 库存数量.
        /// </summary>
        public string inventoryQty { get; set; }

        /// <summary>
        /// 库存责任人.
        /// </summary>
        public string inventoryResponsibleUserId { get; set; }

        /// <summary>
        /// 库存完成日期.
        /// </summary>
        public DateTime? inventoryCompletionDate { get; set; }

        /// <summary>
        /// 是否勾选其他.
        /// </summary>
        public int? isOther { get; set; }

        /// <summary>
        /// 其他数量.
        /// </summary>
        public string otherQyt { get; set; }

        /// <summary>
        /// 其他责任人.
        /// </summary>
        public string otherResponsibleUserId { get; set; }

        /// <summary>
        /// 其他完成日期.
        /// </summary>
        public DateTime? otherCompletionDate { get; set; }

        /// <summary>
        /// 纠正措施.
        /// </summary>
        public string measureRemark { get; set; }

        /// <summary>
        /// 纠正措施责任人.
        /// </summary>
        public string measureResponsibleUserId { get; set; }

        /// <summary>
        /// 纠正措施完成日期.
        /// </summary>
        public DateTime? measureCompletionDate { get; set; }

        /// <summary>
        /// 效果评估.
        /// </summary>
        public string evaluationRemark { get; set; }

        /// <summary>
        /// 效果责任人.
        /// </summary>
        public string evaluationResponsibleUserId { get; set; }

        /// <summary>
        /// 效果完成日期.
        /// </summary>
        public DateTime? evaluationCompletionDate { get; set; }
    }
}
